<template>
  <div class="daily-detail">
    <van-form input-align="right" error-message-align="right" :readonly="!editable" @submit="save" @failed="onValidFail">
      <van-cell-group title="血压">
        <van-field v-model="form.highPress" type="digit" label="收缩压(高压)" placeholder="请输入" :rules="rules.highPress" />
        <van-field v-model="form.lowPress" type="digit" label="舒张压(低压)" placeholder="请输入" :rules="rules.lowPress" />
      </van-cell-group>

      <van-cell-group title="血糖">
        <picker-field v-model="form.bdglType" label="类型" :options="bloodTypeOptions" :rules="rules.picker" :disabled="!editable" />
        <van-field v-if="form.bdglType !== '4'" v-model="form.bloodGlucose" type="digit" label="血糖值" placeholder="请输入" :rules="rules.bloodGlucose" />
      </van-cell-group>

      <van-cell-group title="昨日最终步数">
        <template #title>
          <div class="custom-group-title">
            <span>昨日最终步数</span>
            <van-button v-if="editable" size="small" type="primary" @click="getWeRunData">微信步数</van-button>
          </div>
        </template>
        <van-field v-model="form.stepNum" type="number" label="昨日最终步数" placeholder="请输入" :rules="rules.require" />
      </van-cell-group>

      <van-cell-group title="昨日睡眠">
        <van-field v-model="form.sleepTime" type="digit" label="时间(小时)" placeholder="请输入" :rules="rules.sleepTime" />
        <picker-field v-model="form.sleepQuality" label="质量" :options="sleepQualityOptions" :rules="rules.picker" :disabled="!editable" />
      </van-cell-group>

      <van-cell-group title="运动">
        <picker-field v-model="form.exerciseType" label="类别" :options="sportTypeOptions" :rules="rules.picker" :disabled="!editable" @change="onSportTypeChange" />
        <picker-field v-if="form.exerciseType !== '1'" v-model="form.exerciseOption" label="选项" :options="sportOptions" :disabled="!editable" :rules="rules.picker" />
        <picker-field v-if="form.exerciseType !== '1'" v-model="form.exerciseTime" label="时间" :options="sportTimeOptions" :disabled="!editable" :rules="rules.picker" />
        <van-field v-model="form.sitHour" type="digit" label="静坐时间(小时)" placeholder="请输入" :rules="rules.require" class="van-field-label" />
      </van-cell-group>

      <van-cell-group title="新冠">
        <picker-field v-model="form.crown" label="是否经历新冠" :options="CROWN_OPTIONS" :rules="rules.picker" :disabled="!editable" />
        <template v-if="form.crown === '已感染'">
          <picker-multi-field v-model="form.legacy" label="新冠后遗症" :options="LEGACY_OPTIONS" :rules="rules.picker" :disabled="!editable" />
          <van-field v-model="form.crownOther" label="其他症状(选填)" placeholder="请输入" class="van-field-label" />
        </template>
      </van-cell-group>
      <fixed-bottom v-if="editable">
        <button-group native-type="submit" @cancel="back" />
      </fixed-bottom>
    </van-form>
  </div>
</template>

<script>
import VanField from '@/components/VanField.jsx'
import PickerField from '@/components/PickerField.vue'
import PickerMultiField from '@/components/PickerMultiField.vue'
import ButtonGroup from '@/components/ButtonGroup.vue'
import { CellGroup, Form, Button } from 'vant'
import FixedBottom from '@/components/FixedBottom'
import {
  BLOOD_TYPE_OPTION,
  SLEEP_QUALITY,
  SPORT_TIME,
  SPORT_TYPE,
  SPORT_OPTION,
  dateOfHealthReport,
  saveHealthReport,
  runData,
  CROWN_OPTIONS,
  LEGACY_OPTIONS
} from '../api'
import { validReg, validRange } from '@/utils/validate'
import Taro from '@tarojs/taro'
import { mapGetters } from 'vuex'

export default {
  components: {
    VanField,
    FixedBottom,
    ButtonGroup,
    PickerField,
    PickerMultiField,
    [Form.name]: Form,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup
  },
  data() {
    return {
      bloodTypeOptions: BLOOD_TYPE_OPTION,
      sleepQualityOptions: SLEEP_QUALITY,
      sportTimeOptions: SPORT_TIME,
      sportTypeOptions: SPORT_TYPE,
      sportOptions: SPORT_OPTION,
      CROWN_OPTIONS,
      LEGACY_OPTIONS,
      editable: true,
      form: {
        highPress: '', // 高压
        lowPress: '', // 低压
        bdglType: '', // 血糖类型
        bloodGlucose: '', // 血糖
        stepNum: '', // 步数
        sleepTime: '', // 睡眠时间
        sleepQuality: '', // 睡眠质量
        exerciseType: '', // 运动类别
        exerciseOption: '', // 运动选项
        exerciseTime: '', // 运动时间
        crown: '', // 新冠感染
        legacy: '', // 新冠后遗症
        crownOther: '', // 其他症状
        sitHour: '' // 静坐时间
      },
      rules: {
        highPress: [
          validReg('required'),
          validRange([50, 200], '有效范围50-200')
        ],
        lowPress: [
          validReg('required'),
          validRange([50, 200])
        ],
        picker: [validReg('required', '请选择')],
        bloodGlucose: [validReg('required'), validRange([3, 30])],
        require: [validReg('required')],
        sleepTime: [validReg('required'), validRange([0, 24])]
      },
      wxCode: ''
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  onLoad(options) {
    wx.login({
      success: ({ code }) => {
        this.wxCode = code
      }
    })
    this.getDetail(options.date)
  },
  methods: {
    async save(e) {
      if (this.form.crown !== '已感染') {
        this.form.legacy = ''
        this.form.crownOther = ''
      }
      await saveHealthReport(this.form)
      this.showMsg('已保存', 'success')
      const { crown, legacy, crownOther } = this.form
      this.$store.commit('setUser', Object.assign(this.user, {
        crown,
        crownOther,
        legacy
      }))
      setTimeout(() => {
        this.detailBack({ reload: true })
      }, 1500)
    },
    async getDetail(date) {
      const data = await dateOfHealthReport({ date })
      if (data) {
        this.editable = !!data.editable
        Object.keys(this.form).forEach(key => {
          this.form[key] = data[key]
        })
      } else {
        const { crown = '', legacy = '', crownOther = '' } = this.user
        Object.assign(this.form, {
          crownOther,
          crown,
          legacy
        })
      }
      console.log(date)
    },
    onValidFail(e) {
      console.log(e, 'fail')
      this.showMsg('请检查表单')
    },
    onSportTypeChange(option) {
      if (option.value === '1') {
        this.form.exerciseOption = ''
        this.form.exerciseTime = ''
      }
    },
    getWeRunData() {
      Taro.getSetting({
        success: res => {
          if (!res.authSetting['scope.werun']) {
          // 用户还未授权
            Taro.authorize({
              scope: 'scope.werun',
              success: () => {
              // 读取微信步数
                this.requestWxRunData()
              },
              fail() {
                Taro.showModal({
                  title: '获取微信运动数据失败',
                  content: '请在小程序设置页面（「右上角」-「...」-「设置」）允许我们访问微信运动数据'
                })
              }
            })
          } else {
            this.requestWxRunData()
          }
        }
      })
    },
    requestWxRunData() {
      Taro.getWeRunData({
        success: async({ encryptedData, iv }) => {
          const { step } = await runData({
            encryptedData,
            iv,
            code: this.wxCode
          })
          this.form.stepNum = step
        }
      })
    }
  }
}
</script>

<style lang="less">
@import './index.less';
</style>
